package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.dto.AgentLoginDto;
import cn.chinaflame.pagodas.dto.PaAgentDto;
import cn.chinaflame.pagodas.dto.PaAgentQryDto;
import cn.chinaflame.pagodas.entity.PaAgent;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.handle.HandlerException;
import cn.chinaflame.pagodas.repository.PaAgentRepository;
import cn.chinaflame.pagodas.req.PaAgentQryReq;
import cn.chinaflame.pagodas.req.PaAgentReq;
import cn.chinaflame.pagodas.utils.*;
import cn.chinaflame.pagodas.web.SessionFactory;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author created by lbq
 * @date 2018年1月6日 下午3:31:11
 **/
@Service
public class PaAgentService {
    private static final Logger log = LoggerFactory.getLogger(PaAgentService.class);

    @Autowired
    private PaAgentRepository ywAgentRepository;
    @Autowired
    private CommonService commonService;
    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * 代理登录
     *
     * @param username
     * @param password
     * @return
     */
    public AgentLoginDto login(String username, String password, HttpServletResponse response) {
        log.info("佛龛代理登录【service】username:{},password:{}", username, password);
        PaAgent entity = null;
        ParamPreconditions.checkNotEmpty(username, CodeEnum.FAIL.getCode(), "用户名不能为空");
        ParamPreconditions.checkNotEmpty(password, CodeEnum.FAIL.getCode(), "密码不能为空");
        String loginPwdMd5 = Digests.md5DigestAsHex(password);
        entity = ywAgentRepository.findByMobileAndPwd(username, loginPwdMd5);
        if (entity == null)
            entity = ywAgentRepository.findByLoginIdAndPwd(username, loginPwdMd5);
        if (entity == null)
            entity = ywAgentRepository.findByEmailAndPwd(username, loginPwdMd5);
        ParamPreconditions.checkNotNull(entity, CodeEnum.FAIL.getCode(), "用户名或密码错误");
        SessionFactory.generateSession(entity.getId(), Sysconst.USER_PAGODA_AGENT, entity);
        AgentLoginDto dto = new AgentLoginDto();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }
    
    public void modifyPwd(String oldPwd, String newPwd, String id){
//    	PaAgent agent = SessionFactory.getUserObj(Requests.getSessionIdByCookie(), Sysconst.USER_PAGODA_AGENT, PaAgent.class);
    	PaAgent agent = ywAgentRepository.findOne(id);
    	ParamPreconditions.checkNotNull(agent, CodeEnum.FAIL.getCode(), "未找到登录信息");
    	String oldPwdMd5 = Digests.md5DigestAsHex(oldPwd);
    	ParamPreconditions.checkArgument(Objects.equals(oldPwdMd5, agent.getLoginPwd()), CodeEnum.FAIL.getCode(), "原密码错误");
    	ParamPreconditions.checkNotEmpty(newPwd, CodeEnum.FAIL.getCode(), "新密码不能为空");
    	String newPwdMd5 = Digests.md5DigestAsHex(newPwd);
    	ywAgentRepository.updatePwdById(agent.getId(), newPwdMd5);
    }

    /**
     * 代理添加
     *
     * @param req
     * @return
     */
    public PaAgentDto add(PaAgentReq req) {
        log.info("代理添加【service】req:{}", req);
        String parentId = req.getParentId();
        //判断值是否为1,2,3级代理(只支持1,2,3)
        ParamPreconditions.checkArgument(Sysconst.AgentLevelList.containsKey(req.getAgentLevel()),
                CodeEnum.FAIL.getCode(), "代理等级有误");
        PaAgent parentEntity = null;
        //判断是否有父级代理，有查询父级代理
        if (!Strings.isNullOrEmpty(parentId)) {
            parentEntity = ywAgentRepository.findOne(parentId);
        }
        //代理级别不等于一级代理
        if (!Sysconst.AGENT_LEVEL_ONE.equals(req.getAgentLevel()))
            //判断是否找到父级代理
            ParamPreconditions.checkArgument(!Objects.isNull(parentEntity), CodeEnum.FAIL.getCode(), "未找到父级代理");
        //通过手机号查询代理,因为会员标识有三个，先查手机号是否唯一
        PaAgent entity = ywAgentRepository.findByMobile(req.getMobile());
        //手机号查询未使用，查询会员id看会员ID是否使用
        if (Objects.isNull(entity)) {
            entity = ywAgentRepository.findByLoginId(req.getLoginId());
        }
        //会员ID查询未使用，查询会员邮箱看会员邮箱是否使用
        if (Objects.isNull(entity)) {
            entity = ywAgentRepository.findByEmail(req.getEmail());
        }
        //如果代理不为空，会员标识重复，提示代理人已经存在
        ParamPreconditions.checkArgument(Objects.isNull(entity), CodeEnum.FAIL.getCode(), "代理人已经存在");
        PaAgent newEntity = new PaAgent();
        String agentId = idGeneratorService.generateAgentId();
        BeanUtils.copyProperties(req, newEntity);
        //代理密码为空设置密码为默认密码
        if (Strings.isNullOrEmpty(req.getLoginPwd())) {
            newEntity.setLoginPwd(Digests.md5DigestAsHex(Sysconst.DefaultPwd));
        }

        newEntity.setId(agentId);
        newEntity.setCreatetime(DateTimes.nowDateTime());
        newEntity.setUpdatetime(DateTimes.nowDateTime());
        newEntity = ywAgentRepository.saveAndFlush(newEntity);
        PaAgentDto dto = new PaAgentDto();
        BeanUtils.copyProperties(newEntity, dto);
        return dto;
    }

    /**
     * 根据条件查询代理
     *
     * @param pageIndex
     * @param pageSize
     * @param provinceCode
     * @param cityCode
     * @param areaCode
     * @param projectId
     * @param id
     * @return
     */
    public Result<List<PaAgent>> fingAll(Integer pageIndex, Integer pageSize, String provinceCode, String cityCode, String areaCode, String projectId, String id) {
        log.info("查询代理列表【service】pageIndex:{},pageSize:{},provinceCode:{},cityCode:{},areaCode:{},projectId:{},id:{}", pageIndex, pageSize, provinceCode, cityCode, areaCode, projectId, id);
        //分页不为空
        if (commonService.paginationSupport(pageIndex, pageSize)) {
            Pageable p = new PageRequest(pageIndex - 1, pageSize, new Sort(Direction.DESC, "updatetime"));
            Page<PaAgent> result2 = ywAgentRepository.findAll(new Specification<PaAgent>() {
                @Override
                public Predicate toPredicate(Root<PaAgent> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> list = new ArrayList<Predicate>();
                    if (StringUtils.isNotEmpty(provinceCode)) {
                        list.add(cb.like(root.get("provinceCode").as(String.class), "%" + provinceCode + "%"));
                    }
                    if (StringUtils.isNotEmpty(cityCode)) {
                        list.add(cb.like(root.get("cityCode").as(String.class), "%" + cityCode + "%"));
                    }
                    if (StringUtils.isNotEmpty(areaCode)) {
                        list.add(cb.like(root.get("areaCode").as(String.class), "%" + areaCode + "%"));
                    }
                    if (StringUtils.isNotEmpty(areaCode)) {
                        list.add(cb.equal(root.get("projectId").as(String.class), projectId));
                    }
                    if (StringUtils.isNotEmpty(id)) {
                        list.add(cb.like(root.get("id").as(String.class), "%" + id + "%"));
                    }
                    Predicate[] p = new Predicate[list.size()];
                    return cb.and(list.toArray(p));
                }
            }, p);
            List<PaAgent> list = result2.getContent();
            return Result.create(list);
        }
        List<PaAgent> result = ywAgentRepository.findAll(new Specification<PaAgent>() {
            //传过来分页数据为空
            @Override
            public Predicate toPredicate(Root<PaAgent> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (StringUtils.isNotEmpty(provinceCode)) {
                    list.add(cb.like(root.get("provinceCode").as(String.class), "%" + provinceCode + "%"));
                }
                if (StringUtils.isNotEmpty(cityCode)) {
                    list.add(cb.like(root.get("cityCode").as(String.class), "%" + cityCode + "%"));
                }
                if (StringUtils.isNotEmpty(areaCode)) {
                    list.add(cb.like(root.get("areaCode").as(String.class), "%" + areaCode + "%"));
                }
                if (StringUtils.isNotEmpty(id)) {
                    list.add(cb.like(root.get("id").as(String.class), "%" + id + "%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        return Result.create(result);

    }

    public List<PaAgent> query(String id, String parentId, String provinceCode, String cityCode, String areaCode) {
        log.info("条件查询代理id:{},parentId:{},provinceCode:{},cityCode:{},areaCode:{}", id, parentId, provinceCode, cityCode, areaCode);
        List<PaAgent> entityList = ywAgentRepository.findAll(new Specification<PaAgent>() {
            @Override
            public Predicate toPredicate(Root<PaAgent> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (StringUtils.isNotEmpty(provinceCode)) {
                    list.add(cb.equal(root.get("provinceCode").as(String.class), provinceCode));
                }
                if (StringUtils.isNotEmpty(cityCode)) {
                    list.add(cb.equal(root.get("cityCode").as(String.class), cityCode));
                }
                if (StringUtils.isNotEmpty(areaCode)) {
                    list.add(cb.equal(root.get("areaCode").as(String.class), areaCode));
                }
                if (StringUtils.isNotEmpty(id)) {
                    list.add(cb.equal(root.get("id").as(String.class), id));
                }
                if (StringUtils.isNotEmpty(parentId)) {
                    list.add(cb.equal(root.get("parentId").as(String.class), parentId));
                }
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        return entityList;
    }

    /**
     * 根据代理人id查询代理详情
     *
     * @param id
     * @return
     */
    public Result<List<PaAgentQryDto>> queryByParent(String parentId) {
        log.info("根据父代理id查询代理列表【service】parentId:{}", parentId);
        ParamPreconditions.checkNotEmpty(parentId, CodeEnum.FAIL.getCode(), "父代理id不能为空");
        List<PaAgent> entityList = ywAgentRepository.findByParentId(parentId);
        List<PaAgentQryDto> dtos = Lists.newArrayList();
        for (int i = 0; i < entityList.size(); i++) {
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(entityList.get(i), dto);
            dtos.add(dto);
        }
        return Result.create(dtos);
    }

    public Result<List<PaAgentQryDto>> queryByParentIdAndArea(String parentId, String provinceCode, String cityCode, String areaCode) {
        log.info("根据父代理id查询代理列表【service】parentId:{}", parentId);
        ParamPreconditions.checkNotEmpty(parentId, CodeEnum.FAIL.getCode(), "父代理id不能为空");
        ParamPreconditions.checkNotEmpty(provinceCode, CodeEnum.FAIL.getCode(), "省编码不能为空");
        PaAgent parent = ywAgentRepository.findOne(parentId);
        ParamPreconditions.checkNotNull(parent, CodeEnum.FAIL.getCode(), "父级代理不存在");
        PaAgentQryDto parentDto = new PaAgentQryDto();
        BeanUtils.copyProperties(parent, parentDto);
        List<PaAgent> entityList = ywAgentRepository.findByParentId(parentId);
        List<PaAgentQryDto> dtos = Lists.newArrayList();
        dtos.add(parentDto);
        for (int i = 0; i < entityList.size(); i++) {
            PaAgent agent = entityList.get(i);
            if (provinceCode.equals(agent.getProvinceCode())) {
                PaAgentQryDto dto = new PaAgentQryDto();
                BeanUtils.copyProperties(entityList.get(i), dto);
                dtos.add(dto);
            }
        }
        return Result.create(dtos);
    }

    /**
     * 根据代理人id查询代理详情
     *
     * @param id
     * @return
     */
    public Result<List<PaAgentQryDto>> queryByTree(PaAgentQryReq req) {
        log.info("以树型结构查询代理列表【service】req:{}", req);
        ParamPreconditions.checkNotEmpty(req.getId(), CodeEnum.FAIL.getCode(), "代理id不能为空");
        PaAgent root = null;
        if(!Strings.isNullOrEmpty(req.getId()) && req.getId().startsWith("11") && req.getId().length() == 5){
        	root = ywAgentRepository.findOne("10010");
        	req.setId("10010");
        }else{
        	root = ywAgentRepository.findOne(req.getId());
        }
        ParamPreconditions.checkNotNull(root, CodeEnum.FAIL.getCode(), "未找到代理信息");
        List<PaAgent> list = ywAgentRepository.findByParentId(req.getId());
        PaAgentQryDto rootDto = new PaAgentQryDto();
        BeanUtils.copyProperties(root, rootDto);
        List<PaAgentQryDto> dtos = Lists.newArrayList();
        dtos.add(rootDto);
        for (PaAgent agent : list) {
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(agent, dto);
            dtos.add(dto);
        }
        TreeUtils.createTree(dtos, rootDto, "id", "parentId", "children");
        return Result.create(Lists.newArrayList(rootDto));
//		return 
//		//查询代理信息
//		PaAgent agent = ywAgentRepository.findOne(req.getId());
//		ParamPreconditions.checkNotNull(agent, CodeEnum.FAIL.getCode(), "未找到代理信息");
//		//查询代理等级
//		String level = agent.getAgentLevel();
//		List<PaAgentQryDto> one = Lists.newArrayList();
//		List<PaAgentQryDto> two = Lists.newArrayList();
//		List<PaAgentQryDto> three = Lists.newArrayList();
//		//代理等级等于3级代理
//		if(Sysconst.AGENT_LEVEL_THREE.equals(level)) {
//			//查询父级代理信息
//			PaAgent parent = ywAgentRepository.findOne(agent.getParentId());
//			//代理对象
//			PaAgentQryDto dto = new PaAgentQryDto();
//			BeanUtils.copyProperties(agent, dto);
//			//父级代理对象
//			PaAgentQryDto parentDto = new PaAgentQryDto();
//			BeanUtils.copyProperties(parent, parentDto);
//			//保存父级对象
//			dto.setParent(parentDto);
//			//保存父级对象名称
//			dto.setParentName(parentDto.getName());
//			return Result.create(Lists.newArrayList(dto));
//		//代理等级等于2级代理
//		}else if(Sysconst.AGENT_LEVEL_TWO.equals(level)) {
//			//查询父级代理信息
//			PaAgent parent = ywAgentRepository.findOne(agent.getParentId());
//			//父级代理对象
//			PaAgentQryDto parentDto = new PaAgentQryDto();
//			BeanUtils.copyProperties(parent, parentDto);
//			//父级信息保存到one list
//			one.add(parentDto);
//			//代理对象
//			PaAgentQryDto dto = new PaAgentQryDto();
//			BeanUtils.copyProperties(agent, dto);
//			//代理信息保存到two list
//			two.add(dto);
//			//根据父级代理ID，省编码ID，市编码ID，区编码ID（县编码ID）查询所有代理信息
//			List<PaAgent> threeEntity = query(null, agent.getParentId(), req.getProvinceCode(), req.getCityCode(), req.getAreaCode());
//			for(PaAgent entity : threeEntity) {
//				PaAgentQryDto childDto = new PaAgentQryDto();
//				BeanUtils.copyProperties(entity, childDto);
//				//查询代理信息循环添加three list
//				three.add(childDto);
//			}
//			//查询下级代理数据
//			getDetail(one, two, three);
//			return Result.create(two);
//		//代理等级等于1级代理
//		}else if(Sysconst.AGENT_LEVEL_ONE.equals(level)) {
//			PaAgentQryDto dto = new PaAgentQryDto();
//			BeanUtils.copyProperties(agent, dto);
//			one.add(dto);
//			List<PaAgent> twoEntity = query(null, agent.getId(), req.getProvinceCode(), req.getCityCode(), req.getAreaCode());
//			List<PaAgent> threeEntity = ywAgentRepository.findByLevel(Sysconst.AGENT_LEVEL_THREE);
//			for(PaAgent entity : twoEntity) {
//				PaAgentQryDto dto1 = new PaAgentQryDto();
//				BeanUtils.copyProperties(entity, dto1);
//				two.add(dto1);
//			}
//			for(PaAgent entity : threeEntity) {
//				PaAgentQryDto dto1 = new PaAgentQryDto();
//				BeanUtils.copyProperties(entity, dto1);
//				three.add(dto1);
//			}
//			getDetail(one, two, three);
//			return Result.create(one);
//		}else 
//			throw new HandlerException("错误的代理级别","错误的代理级别","错误的代理级别");
    }

    /**
     * 根据代理人id查询代理详情
     *
     * @param id
     * @return
     */
    public Result<List<PaAgentQryDto>> queryById(String id) {
        log.info("树型结构查询代理列表【service】id:{}", id);
        ParamPreconditions.checkNotEmpty(id, CodeEnum.FAIL.getCode(), "代理id不能为空");
        PaAgent agent = ywAgentRepository.findOne(id);
        ParamPreconditions.checkNotNull(agent, CodeEnum.FAIL.getCode(), "未找到代理信息");
        String level = agent.getAgentLevel();
        List<PaAgentQryDto> one = Lists.newArrayList();
        List<PaAgentQryDto> two = Lists.newArrayList();
        List<PaAgentQryDto> three = Lists.newArrayList();
        if (Sysconst.AGENT_LEVEL_THREE.equals(level)) {
            PaAgent parent = ywAgentRepository.findOne(agent.getParentId());
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(agent, dto);
            PaAgentQryDto parentDto = new PaAgentQryDto();
            BeanUtils.copyProperties(parent, parentDto);
            dto.setParent(parentDto);
            dto.setParentName(parentDto.getName());
            return Result.create(Lists.newArrayList(dto));
        } else if (Sysconst.AGENT_LEVEL_TWO.equals(level)) {
            PaAgent parent = ywAgentRepository.findOne(agent.getParentId());
            PaAgentQryDto parentDto = new PaAgentQryDto();
            BeanUtils.copyProperties(parent, parentDto);
            one.add(parentDto);
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(agent, dto);
            two.add(dto);
            List<PaAgent> threeEntity = ywAgentRepository.findByParentId(agent.getId());
            for (PaAgent entity : threeEntity) {
                PaAgentQryDto childDto = new PaAgentQryDto();
                BeanUtils.copyProperties(entity, childDto);
                three.add(childDto);
            }
            getDetail(one, two, three);
            return Result.create(two);
        } else if (Sysconst.AGENT_LEVEL_ONE.equals(level)) {
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(agent, dto);
            one.add(dto);
            List<PaAgent> twoEntity = ywAgentRepository.findByLevel(Sysconst.AGENT_LEVEL_TWO);
            List<PaAgent> threeEntity = ywAgentRepository.findByLevel(Sysconst.AGENT_LEVEL_THREE);
            for (PaAgent entity : twoEntity) {
                PaAgentQryDto dto1 = new PaAgentQryDto();
                BeanUtils.copyProperties(entity, dto1);
                two.add(dto1);
            }
            for (PaAgent entity : threeEntity) {
                PaAgentQryDto dto1 = new PaAgentQryDto();
                BeanUtils.copyProperties(entity, dto1);
                three.add(dto1);
            }
            ;
            return Result.create(getDetail(one, two, three));
        } else
            throw new HandlerException("错误的代理级别", "错误的代理级别", "错误的代理级别");
    }

    /**
     * 根据代理人id查询代理详情
     *
     * @param id
     * @return
     */
    public Result<List<PaAgentQryDto>> queryByProjectId(String projectId) {
        log.info("树型结构查询所有代理【service】projectId:{}", projectId);
        List<PaAgent> oneEntity = ywAgentRepository.findByLevel(Sysconst.AGENT_LEVEL_ONE);
        List<PaAgent> twoEntity = ywAgentRepository.findByLevel(Sysconst.AGENT_LEVEL_TWO);
        List<PaAgent> threeEntity = ywAgentRepository.findByLevel(Sysconst.AGENT_LEVEL_THREE);
        List<PaAgentQryDto> one = Lists.newArrayList();
        List<PaAgentQryDto> two = Lists.newArrayList();
        List<PaAgentQryDto> three = Lists.newArrayList();
        for (PaAgent entity : oneEntity) {
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(entity, dto);
            one.add(dto);
        }
        for (PaAgent entity : twoEntity) {
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(entity, dto);
            two.add(dto);
        }
        for (PaAgent entity : threeEntity) {
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(entity, dto);
            three.add(dto);
        }
        return Result.create(getDetail(one, two, three));
    }

    /**
     * @param one   一级代理信息	list
     * @param two   二级代理信息	list
     * @param three 三级代理信息	list
     * @return
     */
    private List<PaAgentQryDto> getDetail(List<PaAgentQryDto> one, List<PaAgentQryDto> two, List<PaAgentQryDto> three) {
        //判断一级代理数据是否为空
        if (one.size() > 0) {
            //循环取出一级代理信息
            for (PaAgentQryDto oneDto : one) {
                List<PaAgentQryDto> oneChildren = Lists.newArrayList();
                //判断二级代理数据是否为空
                if (two.size() > 0) {
                    //循环取出二级代理信息
                    for (PaAgentQryDto twoDto : two) {
                        List<PaAgentQryDto> twoChildren = Lists.newArrayList();
                        //判断三级代理数据是否为空
                        if (three.size() > 0) {
                            //循环取出三级代理信息
                            for (PaAgentQryDto threeDto : three) {
                                //判断当条数据二级代理ID和当条三级代理数据父机代理ID是否相同
                                if (twoDto.getId().equals(threeDto.getParentId())) {
                                    //二级代理数据存入当前三级代理DTO
                                    threeDto.setParent(twoDto);
                                    //二级代理名称存入当前三级代理DTO
                                    threeDto.setParentName(twoDto.getName());
                                    //三级代理存入二级代理twoChildren list
                                    twoChildren.add(threeDto);
                                }
                            }
                        }
                        //判断当条数据一级代理ID和当条二级代理数据父机代理ID是否相同
                        if (twoDto != null && twoDto.getParentId().equals(oneDto.getId())) {
                            //一级代理数据存入当前二级代理DTO
                            twoDto.setParent(oneDto);
                            //一级代理名称存入当前二级代理DTO
                            twoDto.setParentName(oneDto.getName());
                            //二级代理存入一级代理twoChildren list
                            oneChildren.add(twoDto);
                        }
                        //二级代理名下三级代理信息存入二级代理DTO
                        twoDto.setChildren(twoChildren);
                    }
                    //一级代理名下二级代理信息，二级代理名下三级代理信息存入一级代理
                    oneDto.setChildren(oneChildren);
                }
            }
        }

        return one;
    }

    /**
     * 根据代理人id查询代理详情
     *
     * @param id
     * @return
     */
    public Result<PaAgentQryDto> query(String id) {
        log.info("根据代理人id查询代理详情id:{}", id);
        ParamPreconditions.checkNotEmpty(id, CodeEnum.FAIL.getCode(), "代理人id不能为空");
        PaAgent entity = ywAgentRepository.findOne(id);
        ParamPreconditions.checkNotNull(entity, CodeEnum.FAIL.getCode(), "未找到代理信息");
        PaAgentQryDto dto = new PaAgentQryDto();
        BeanUtils.copyProperties(entity, dto);
        return Result.create(dto);
    }

    /**
     * 更新代理人
     *
     * @param dto
     * @return
     */
    public PaAgentDto updateAgent(PaAgentDto dto) {
        log.info("更新代理人dto:{}", dto);
        ParamPreconditions.checkNotEmpty(dto.getId(), CodeEnum.FAIL.getCode(), "更新代理人id为空");
        PaAgent agent = ywAgentRepository.findOne(dto.getId());
        ParamPreconditions.checkArgument(agent != null, CodeEnum.FAIL.getCode(), "没有该代理人");
        agent.setUpdatetime(DateTimes.nowDateTime());
        BeanUtils.copyProperties(dto, agent);
        ywAgentRepository.saveAndFlush(agent);
        return dto;
    }

    public String queryAryId(String id) {
        Result<List<PaAgentQryDto>> rs = queryById(id);
        List<PaAgentQryDto> pq = rs.getData();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < pq.size(); i++) {
            sb.append(pq.get(0).getId());
            if (pq.get(0).getChildren() != null) {
                List<PaAgentQryDto> pq1 = pq.get(0).getChildren();
                for (int j = 0; j < pq1.size(); j++) {
                    sb.append("," + pq1.get(j).getId());
                    if (pq1 != null) {
                        List<PaAgentQryDto> pq2 = pq1.get(j).getChildren();
                        for (int k = 0; k < pq2.size(); k++) {
                            sb.append("," + pq2.get(k).getId());
                        }
                    }
                }
            }
        }
        String str = sb.toString();
        return str;
    }

    public Result<PaAgentQryDto> test() {
        List<PaAgent> agents = ywAgentRepository.findAll();
        List<PaAgentQryDto> dtos = Lists.newArrayList();
        for (PaAgent agent : agents) {
            PaAgentQryDto dto = new PaAgentQryDto();
            BeanUtils.copyProperties(agent, dto);
            dtos.add(dto);
        }
        List<PaAgent> rootAgents = ywAgentRepository.findByParentId(Sysconst.TREE_ROOT_PARENT);
        PaAgent rootAgent = rootAgents.get(0);
        PaAgentQryDto rootDto = new PaAgentQryDto();
        BeanUtils.copyProperties(rootAgent, rootDto);
        TreeUtils.createTree(dtos, rootDto, "id", "parentId", "children");
        System.out.println(Jackson.writeJson(rootDto));
        return null;
    }

    public void test1() {

    }


}








